<template>
  <!-- 图表区域 -->
  <div class="flex justify-between mx-5">
    <ECharts :options="chartOptions" class="home-chart" />
    <ECharts :options="incomeChartOptions" class="home-chart" />
    <div class="w-3xs h-[330px] flex justify-between flex-col">
      <!-- 未收款 -->
      <div class="home-right" @click="toPay">
          <div class="box">
            <span>未收款</span>
            <p class="text">{{ noPayOrderCount }}</p>
          </div>
          <div class="ico bg-[#FF6800] ">
            <el-icon size="40" color="white"><Wallet/></el-icon>
          </div>
      </div>
      <!-- 到期提醒 -->
      <div class="home-right" @click="toRemind">
          <div class="box">
            <span>到期提醒</span>
            <p class="text">{{ expiringContracts }}</p>
          </div>
          <div class="ico bg-[#259B24]">
            <el-icon size="40" color="white"><Bell /></el-icon>
          </div>
      </div>
      <!-- 投诉管理 -->
      <div class="home-right" @click="toComplaint">
          <div class="box">
            <span>投诉管理</span>
            <p class="text">{{ complaintCount }}</p>
          </div>
          <div class="ico bg-[#3DBFBF]">
            <el-icon size="40" color="white"><Service /></el-icon>
          </div>
      </div>
    </div>
  </div>
  <!-- 排单情况 -->
  <div class="h-96 bg-white mt-3 p-3 mx-5">
    <Bar>
      <span class="bar-span">明日排单情况</span>
    </Bar>
    <el-divider />
    <div class="flex order-section-flex">
      <!-- 订单状态 -->
      <div class="w-[50%]">
        <div class="text-sm ml-3 text-[#666666]">订单状态</div>
        <div class="flex order-section-flex">
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.orderStatus.total_orders }}</span>
              <p class="text-detail">订单总量</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.orderStatus.assigned_orders }}</span>
              <p class="text-detail">已派单</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text-[#E51C23] text-2xl">{{ orderStats.orderStatus.unassigned_orders }}</span>
              <p class="text-detail">未派单</p>
            </div>
          </div>
        </div>
      </div>
      <!-- 客户类型 -->
      <div class="w-[50%]">
        <div class="text-sm ml-5 text-[#666666]">客户类型</div>
        <div class="flex order-section-flex">
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.customerType.temporary_orders }}</span>
              <p class="text-detail">临时订单</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.customerType.monthly_orders }}</span>
              <p class="text-detail">包月订单</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.customerType.quarterly_orders }}</span>
              <p class="text-detail">包季订单</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.customerType.yearly_orders }}</span>
              <p class="text-detail">包年订单</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-divider />
    <div class="flex order-section-flex">
      <!-- 时间档期 -->
      <div class="w-[50%]">
        <div class="text-sm ml-3 text-[#666666]">时间档期</div>
        <div class="flex order-section-flex">
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.timeSlot.morning_early }}</span>
              <p class="text-detail">上午8:00~10:00</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.timeSlot.morning_late }}</span>
              <p class="text-detail">上午10:30~12:30</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.timeSlot.afternoon_early }}</span>
              <p class="text-detail">下午2:00~4:00</p>
            </div>
          </div>
          <div class="home-bottom">
            <div class="box">
              <span class="text">{{ orderStats.timeSlot.afternoon_late }}</span>
              <p class="text-detail">下午4:30~6:30</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="charts">
import * as echarts from "echarts";
import ECharts from '@/components/ECharts.vue';
import { Wallet, Bell, Service } from '@element-plus/icons-vue'
import { useRouter } from "vue-router";
import Bar from "@/components/Bar.vue";
import { useNoPayStore } from "@/stores/useNoPayStore";
import { onMounted, ref } from "vue";
import instance from "@/api";
import { ElMessage } from "element-plus";
interface OrderStatistics {
  orderStatus: {
    total_orders: number;
    assigned_orders: number;
    unassigned_orders: number;
  };
  customerType: {
    temporary_orders: number;
    monthly_orders: number;
    quarterly_orders: number;
    yearly_orders: number;
  };
  timeSlot: {
    morning_early: number;
    morning_late: number;
    afternoon_early: number;
    afternoon_late: number;
  };
}
const orderStats = ref<OrderStatistics>({
  orderStatus: { total_orders: 0, assigned_orders: 0, unassigned_orders: 0 },
  customerType: { temporary_orders: 0, monthly_orders: 0, quarterly_orders: 0, yearly_orders: 0 },
  timeSlot: { 
    morning_early: 0,
    morning_late: 0,
    afternoon_early: 0, 
    afternoon_late: 0 
  }
});

// 添加近七天订单量数据
const sevenDaysData = ref({
  dates: [] as string[],
  orderCounts: [] as number[],
  incomes: [] as number[]
});

const noPayStore = useNoPayStore()
const router = useRouter()
const noPayOrderCount = ref(0)
const complaintCount = ref(0)
const expiringContracts = ref(0)
const chartOptions = ref<any>({
  title: {
    text: '近七天订单量',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#999'
      }
    }
  },
  xAxis: {
    type: 'category',
    data: sevenDaysData.value.dates,
    boundaryGap: false
  },
  yAxis: {
    type: 'value',
    min: 0
  },
  series: [{
    type: 'line',
    data: sevenDaysData.value.orderCounts,
    smooth: true,
    symbol: 'circle',
    symbolSize: 4,
    itemStyle: {
      color: '#fff',
      borderColor: '#79bbff',
      borderWidth: 1
    },
    lineStyle: {
      color: '#79bbff',
      width: 2
    },
    areaStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(121, 187, 255, 0.2)' },
        { offset: 1, color: 'rgba(121, 187, 255, 0)' }
      ])
    }
  }]
});

const incomeChartOptions = ref<any>({
  title: {
    text: '近七天收入',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: '#999'
      }
    }
  },
  xAxis: {
    type: 'category',
    data: ['6.22', '6.23', '6.24', '6.25', '6.26', '6.27', '6.28'],
    boundaryGap: false
  },
  yAxis: {
    type: 'value',
    min: 0,
    max: 800
  },
  series: [{
    type: 'line',
    data: [80, 120, 268.7, 220, 240, 260, 380],
    smooth: true,
    symbol: 'circle',
    symbolSize: 4,
    itemStyle: {
      color: '#fff',
      borderColor: '#79bbff',
      borderWidth: 1
    },
    lineStyle: {
      color: '#79bbff',
      width: 2
    },
    areaStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(121, 187, 255, 0.2)' },
        { offset: 1, color: 'rgba(121, 187, 255, 0)' }
      ])
    }
  }]
});

function toPay(){
  router.push({ name: 'pay' })
}
function toRemind(){
  router.push({ name: 'remind' })
}
function toComplaint(){
  router.push({ name: 'complaint' })
} 
const getComplaintCount = async () => {
  const response = await instance.get('/api/complaint/count', {
    params: {
      status: '未处理'
    }
  })
  const { data } = response
  complaintCount.value = data
}
const getExpiringContracts = async () => {
  const response = await instance.get('/api/contract/expirationCount')
  const { data } = response
  expiringContracts.value = data
}
const fetchOrderStats = async () => {
  try {
    const { data } = await instance.get<OrderStatistics>('/api/statistics/tomorrow-orders');
    orderStats.value = data;
  } catch (error) {
    console.error('获取订单统计数据失败:', error);
  }
};

// 获取近七天订单量数据
const getSevenDaysOrderData = async () => {
  try {
    const response = await instance.get('/api/statistics/last-seven-days');
    const { orderTimeStatistics } = response.data;
    orderTimeStatistics.dates.shift()
    orderTimeStatistics.orderCounts.shift()
    orderTimeStatistics.orderAmounts.shift()
    sevenDaysData.value = {
      dates: orderTimeStatistics.dates,
      orderCounts: orderTimeStatistics.orderCounts,
      incomes: orderTimeStatistics.orderAmounts
    };
    
    // 更新订单量图表
    const orderOptions: any = chartOptions.value;
    orderOptions.xAxis.data = orderTimeStatistics.dates;
    orderOptions.series[0].data = orderTimeStatistics.orderCounts;
    chartOptions.value = { ...orderOptions };
    
    // 更新收入图表
    const incomeOptions: any = incomeChartOptions.value;
    incomeOptions.xAxis.data = orderTimeStatistics.dates;
    incomeOptions.series[0].data = orderTimeStatistics.orderAmounts;
    // 动态设置y轴最大值
    const maxIncome = Math.max(...orderTimeStatistics.orderAmounts);
    incomeOptions.yAxis.max = Math.ceil(maxIncome / 100) * 100; // 向上取整到最近的100
    incomeChartOptions.value = { ...incomeOptions };
  } catch (error) {
    console.error('获取近七天订单量数据失败:', error);
  }
};

onMounted(() => {
  instance.get('/api/order/noPayOrder').then(resp => {
    const { data, status } = resp
    console.log(resp)
    if(status === 401){
      ElMessage.error('身份过期请重新登录')
    }
    noPayOrderCount.value = data.length
    noPayStore.setNoPayOrderCount(data.length)
    noPayStore.setNoPayData(data)
  })
  getComplaintCount()
  getExpiringContracts()
  fetchOrderStats()
  getSevenDaysOrderData() // 添加获取近七天订单量数据的调用
})
</script>

<style scoped>
.el-divider--horizontal{
  margin: 10px 0;
}
.home-chart{
  flex: 1;
  min-width: 0;
}
.home-chart:not(:last-child) {
  margin-right: 16px; /* 或你想要的间距 */
}
.home-right{
  width: 100%;
  display: flex;
  padding: 8px 20px;
  background-color: white;
  cursor: pointer;
}
.home-right .box{
  width: 60%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.home-right .text{
  font-size: 24px;
  color: #FF6800;
}
.home-right .ico{
  width: 40%;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
}
.home-bottom{
  width: 25%;
  height: 112px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-right: 1px solid #f0f0f0;
}
.home-bottom .box{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.home-bottom .text{
  font-size: 24px;
  color: #259B24;
}
.home-bottom .text-detail{
  font-size: 14px;
  margin-top: 4px;
}
@media (max-width: 768px) {
  .flex.justify-between.mx-5 {
    flex-direction: column !important;
    align-items: stretch !important;
    margin: 0;
  }
  .home-chart {
    margin-right: 0 !important;
    margin-bottom: 16px;
    min-height: 220px;
    background: #fff;
  }
  .w-3xs {
    width: 100% !important;
    margin-bottom: 16px;
  }
  .h-96.bg-white.mt-3.p-3.mx-5 {
    padding: 12px 0 !important;
    margin: 12px 0 !important;
    min-height: unset !important;
  }
  .w-\[50\%\], .ml-3, .ml-5 {
    width: 100% !important;
    margin-left: 0 !important;
  }
  .order-section-flex {
    flex-direction: column !important;
    width: 100% !important;
    margin: 0 !important;
    padding: 0 2px;
  }
  .home-bottom {
    width: 100% !important;
    height: auto !important;
    border-right: none !important;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 10px;
    padding: 16px 0 10px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.03);
  }
  .home-bottom:last-child {
    border-bottom: none;
  }
  .home-bottom .box {
    width: 100%;
    align-items: center;
  }
  .home-bottom .text {
    font-size: 26px;
    color: #259B24;
    font-weight: bold;
  }
  .home-bottom .text-detail {
    font-size: 16px;
    margin-top: 8px;
    color: #666;
  }
  .text-sm {
    padding-left: 8px;
    font-size: 17px;
    margin-bottom: 8px;
    font-weight: bold;
  }
  .el-divider--horizontal {
    margin: 8px 0;
  }
}
</style>